import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-07-17
 * Time: 19:40
 */
// key-value 模型
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return -1;
            }
            cur = cur.next;
        }
        Node newNode = new Node(key,value);
        newNode.next = array[index];
        array[index] = newNode;
        size++;
        if(loadFactor() > LOAD_FACTOR) {
            resize();
        }

        return 1;
    }


    private void resize() {
        // write code here
        int size = array.length;
        this.array = Arrays.copyOf(array,(array.length) * 2);
        for(int i = 0; i < size; i++) {
            Node cur = array[i];
            while(cur != null) {
                int index = cur.key % array.length;
                Node nextNode = cur.next;
                Node tmp = array[index];
                cur.next = array[index];
                array[index] = cur;
                cur = nextNode;
            }
        }
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
        array = new Node[10];
    }


    public int get(int key) {
        // write code here
        for(int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                if(cur.key == key) {
                    return cur.value;
                }
                cur = cur.next;
            }
        }

        return -1;
    }
}
